<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $email
 * @property string $password
 * @property string $roles
 * @property string $truename
 * @property string $idcard
 * @property string $gender
 * @property string $birthday
 * @property string $city
 * @property string $mobile
 * @property string $qq
 * @property string $company
 * @property string $job
 * @property string $class
 * @property string $student_id
 * @property string $weixin
 * @property string $iam
 * @property integer $loginTime
 * @property string $loginIp
 * @property string $createdIp
 * @property integer $createdTime
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    public $authKey;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email', 'password', 'roles', 'class'], 'required','message' => '不能为空'],
            [['email'], 'email','message' => '邮箱地址不正确'],
            [['gender'], 'string'],
            [['birthday'], 'safe'],
            [['loginTime', 'createdTime'], 'integer'],
            [['email'], 'string', 'max' => 128],
            [['password', 'city', 'loginIp', 'createdIp'], 'string', 'max' => 64],
            [['roles', 'truename', 'company', 'job', 'class', 'student_id', 'weixin', 'iam'], 'string', 'max' => 255],
            [['idcard'], 'string', 'max' => 24],
            [['mobile', 'qq'], 'string', 'max' => 32],
            [['email'], 'unique','message' => '邮箱不能重复'],
            [['student_id'], 'unique','message' => '学号不能重复']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '用户ID',
            'email' => '用户邮箱',
            'password' => '用户密码',
            'roles' => '用户角色',
            'truename' => '真实姓名',
            'idcard' => '身份证号码',
            'gender' => '性别',
            'birthday' => '生日',
            'city' => '城市',
            'mobile' => '手机',
            'qq' => 'QQ',
            'company' => '公司',
            'job' => '就业情况',
            'class' => '班级',
            'student_id' => '学号',
            'weixin' => '微信',
            'iam' => '简介',
            'loginTime' => '最后登录时间',
            'loginIp' => '最后登录IP',
            'createdIp' => '注册IP',
            'createdTime' => '注册时间',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id) {
        $user = self::findById($id);
        if ($user) {
            return new static($user);
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        $user = User::find()->where(array('accessToken' => $token))->one();
        if ($user) {
            return new static($user);
        }
        return null;
    }

    /**
     * Finds user by username
     *
     * @param  string      $email
     * @return static|null
     */
    public static function findByUsername($email) {
        $user = User::find()->where(array('email' => $email))->one();
        if ($user) {
            return new static($user);
        }

        return null;
    }

    public static function findById($id) {
        $user = User::find()->where(array('id' => $id))->asArray()->one();
        if ($user) {
            return new static($user);
        }

        return null;
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     * 在创建用户的时候，也需要对密码进行操作
     */
    public function validatePassword($password) {
        //方法一:使用自带的加密方式
        return $this->password === md5($password);

        //方法二：通过YII自带的验证方式来验证hash是否正确
        //return Yii::$app->getSecurity()->validatePassword($password, $this->password);
    }

    /**
     * @param $id
     * @return array
     * 获取个人战绩
     */
    public static function getRatesForUserByUid($id){
        $rates = array();
        if(Yii::$app->db->createCommand("select * from attendance where uid = '{$id}'")->queryOne()){
            $rates['attendance'] = Yii::$app->db->createCommand("select sum(gender)/count(*)*100 attendance from attendance where uid = '{$id}'")->queryScalar();
        }else{
            $rates['attendance'] = 100;
        }
        if(Yii::$app->db->createCommand("select * from homework where uid = '{$id}'")->queryOne()){
            $rates['homework'] = round(Yii::$app->db->createCommand("select (sum(score)/(count(*)*100))*100 homework from homework where uid = '{$id}'")->queryScalar());
        }else{
            $rates['homework'] = 100;
        }
        if(Yii::$app->db->createCommand("select * from test where uid = '{$id}'")->queryOne()){
            $rates['test'] = round(Yii::$app->db->createCommand("select (sum(score)/(count(*)*100))*100 test from test where uid = '{$id}'")->queryScalar());
        }else{
            $rates['test'] = 100;
        }

        $rates['avg'] = round(($rates['attendance']+$rates['homework']+$rates['test'])/3);
        return $rates;
    }
}
